﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace EXCEL_LIB
{
    public class ExcelSession
    {
        private static object m = System.Reflection.Missing.Value;
        private static object otrue = true;
        private static object ofalse = false;
        Excel.Application excel;
        Excel.Workbook wb;
        Excel.Worksheet ws;

        public ExcelSession()
        {
            excel = new Excel.Application();
        }

        public Excel.Worksheet Open(string path)
        {
            wb = excel.Workbooks.Open(path, m, otrue, m, m, m, otrue, m, m, m, m, m, m, m, m);
            ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
            return ws;
        }

        private void ReleaseObject(object obj)
        {
            Marshal.ReleaseComObject(obj);
            GC.Collect();
        }

        public void Save(string path)
        {
            object opath = (object)path;
            wb.SaveAs(opath, m, m, m, m, m, Excel.XlSaveAsAccessMode.xlExclusive, m, m, m, m);
        }

        public void Close()
        {
            wb.Close(ofalse, m, m);
        }

        public void Quit()
        {
            excel.Quit();
            ReleaseObject(ws);
            ReleaseObject(wb);
            ReleaseObject(excel);
        }
    }
}
